#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AI营销方案生成系统 - 中间件模块
提供Flask应用的中间件功能

主要功能：
- 请求/响应处理
- 认证和授权
- 限流和安全
- 日志记录
- 错误处理

设计原则：
- 链式处理：中间件按顺序执行
- 可配置：支持动态启用/禁用
- 高性能：最小化处理开销
- 可扩展：易于添加新的中间件

Author: AI Marketing System
Date: 2024
"""

from flask import Flask

# 导入所有中间件
from .request_id import RequestIdMiddleware
from .auth import AuthMiddleware
from .rate_limit import RateLimitMiddleware
from .cors import CorsMiddleware
from .logging import LoggingMiddleware
from .error_handler import ErrorHandlerMiddleware
from .security import SecurityMiddleware
from .cache import CacheMiddleware
from .compression import CompressionMiddleware
from .monitoring import MonitoringMiddleware

# 中间件注册表
MIDDLEWARE_REGISTRY = {
    'request_id': RequestIdMiddleware,
    'auth': AuthMiddleware,
    'rate_limit': RateLimitMiddleware,
    'cors': CorsMiddleware,
    'logging': LoggingMiddleware,
    'error_handler': ErrorHandlerMiddleware,
    'security': SecurityMiddleware,
    'cache': CacheMiddleware,
    'compression': CompressionMiddleware,
    'monitoring': MonitoringMiddleware
}

# 默认中间件执行顺序
DEFAULT_MIDDLEWARE_ORDER = [
    'request_id',      # 生成请求ID
    'logging',         # 请求日志记录
    'monitoring',      # 性能监控
    'security',        # 安全检查
    'cors',           # CORS处理
    'compression',     # 响应压缩
    'rate_limit',     # 限流控制
    'auth',           # 认证授权
    'cache',          # 缓存处理
    'error_handler'   # 错误处理
]


class MiddlewareManager:
    """
    中间件管理器
    负责中间件的注册、配置和执行
    """
    
    def __init__(self, app: Flask = None):
        """
        初始化中间件管理器
        
        Args:
            app: Flask应用实例
        """
        self.app = app
        self.middlewares = {}
        self.middleware_order = DEFAULT_MIDDLEWARE_ORDER.copy()
        self.enabled_middlewares = set()
        
        if app:
            self.init_app(app)
    
    def init_app(self, app: Flask):
        """
        初始化Flask应用
        
        Args:
            app: Flask应用实例
        """
        self.app = app
        
        # 从配置中获取中间件设置
        middleware_config = app.config.get('MIDDLEWARE_CONFIG', {})
        
        # 注册中间件
        self.register_middlewares(middleware_config)
        
        # 设置中间件执行顺序
        custom_order = middleware_config.get('order', [])
        if custom_order:
            self.set_middleware_order(custom_order)
        
        # 启用默认中间件
        default_enabled = middleware_config.get('enabled', list(MIDDLEWARE_REGISTRY.keys()))
        for middleware_name in default_enabled:
            self.enable_middleware(middleware_name)
    
    def register_middleware(self, name: str, middleware_class, config: dict = None):
        """
        注册单个中间件
        
        Args:
            name: 中间件名称
            middleware_class: 中间件类
            config: 中间件配置
        """
        if not self.app:
            raise RuntimeError("Flask应用未初始化")
        
        # 创建中间件实例
        middleware_instance = middleware_class(self.app, config or {})
        self.middlewares[name] = middleware_instance
        
        # 如果中间件不在执行顺序中，添加到末尾
        if name not in self.middleware_order:
            self.middleware_order.append(name)
    
    def register_middlewares(self, config: dict = None):
        """
        批量注册中间件
        
        Args:
            config: 中间件配置字典
        """
        config = config or {}
        
        for name, middleware_class in MIDDLEWARE_REGISTRY.items():
            middleware_config = config.get(name, {})
            self.register_middleware(name, middleware_class, middleware_config)
    
    def enable_middleware(self, name: str):
        """
        启用中间件
        
        Args:
            name: 中间件名称
        """
        if name not in self.middlewares:
            raise ValueError(f"中间件 '{name}' 未注册")
        
        self.enabled_middlewares.add(name)
        
        # 启用中间件
        middleware = self.middlewares[name]
        if hasattr(middleware, 'enable'):
            middleware.enable()
    
    def disable_middleware(self, name: str):
        """
        禁用中间件
        
        Args:
            name: 中间件名称
        """
        if name in self.enabled_middlewares:
            self.enabled_middlewares.remove(name)
        
        # 禁用中间件
        if name in self.middlewares:
            middleware = self.middlewares[name]
            if hasattr(middleware, 'disable'):
                middleware.disable()
    
    def set_middleware_order(self, order: list):
        """
        设置中间件执行顺序
        
        Args:
            order: 中间件名称列表
        """
        # 验证所有中间件都已注册
        for name in order:
            if name not in MIDDLEWARE_REGISTRY:
                raise ValueError(f"未知的中间件: {name}")
        
        self.middleware_order = order
    
    def get_enabled_middlewares(self) -> list:
        """
        获取已启用的中间件列表（按执行顺序）
        
        Returns:
            已启用的中间件实例列表
        """
        enabled_middlewares = []
        
        for name in self.middleware_order:
            if name in self.enabled_middlewares and name in self.middlewares:
                enabled_middlewares.append(self.middlewares[name])
        
        return enabled_middlewares
    
    def get_middleware_stats(self) -> dict:
        """
        获取中间件统计信息
        
        Returns:
            统计信息字典
        """
        stats = {
            'total_registered': len(self.middlewares),
            'total_enabled': len(self.enabled_middlewares),
            'execution_order': self.middleware_order,
            'enabled_middlewares': list(self.enabled_middlewares),
            'middleware_details': {}
        }
        
        for name, middleware in self.middlewares.items():
            middleware_stats = {
                'enabled': name in self.enabled_middlewares,
                'class': middleware.__class__.__name__
            }
            
            # 获取中间件特定的统计信息
            if hasattr(middleware, 'get_stats'):
                middleware_stats.update(middleware.get_stats())
            
            stats['middleware_details'][name] = middleware_stats
        
        return stats


# 全局中间件管理器实例
middleware_manager = MiddlewareManager()


def init_middleware(app: Flask, config: dict = None):
    """
    初始化中间件系统
    
    Args:
        app: Flask应用实例
        config: 中间件配置
    """
    # 设置中间件配置
    if config:
        app.config['MIDDLEWARE_CONFIG'] = config
    
    # 初始化中间件管理器
    middleware_manager.init_app(app)
    
    return middleware_manager


def get_middleware_manager() -> MiddlewareManager:
    """
    获取中间件管理器实例
    
    Returns:
        中间件管理器实例
    """
    return middleware_manager


# 导出的中间件类和函数
__all__ = [
    # 中间件类
    'RequestIdMiddleware',
    'AuthMiddleware',
    'RateLimitMiddleware',
    'CorsMiddleware',
    'LoggingMiddleware',
    'ErrorHandlerMiddleware',
    'SecurityMiddleware',
    'CacheMiddleware',
    'CompressionMiddleware',
    'MonitoringMiddleware',
    
    # 管理器类
    'MiddlewareManager',
    
    # 全局实例
    'middleware_manager',
    
    # 工具函数
    'init_middleware',
    'get_middleware_manager',
    
    # 常量
    'MIDDLEWARE_REGISTRY',
    'DEFAULT_MIDDLEWARE_ORDER'
]

# 版本信息
__version__ = '1.0.0'
__author__ = 'AI Marketing System'
__description__ = 'Middleware module for AI Marketing System'